package com.sam.im.heiqun.uis.activities;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.GroupFriendEntivity;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImGroupEntivity;
import com.sam.im.heiqun.entities.SearchUserEntity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.GroupLevelAdapter;
import com.sam.im.heiqun.uis.beans.GroupLevelBean;
import com.sam.im.heiqun.uis.beans.GroupLevelEntity;
import com.sam.im.heiqun.utils.MyDialog;
import com.sam.im.heiqun.utils.RSAUtils;
import com.sam.im.heiqun.utils.RequestRSAUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.toast.ToastUtils;
import com.yuyh.library.view.text.PasswordEditText;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;

/**
 * Created by wangguodong on 2018/1/8.
 */

public class GroupLevelSelectActivity extends BaseSwipeBackActivity {
//GroupLevelAdapter
    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;

    private PGService mPGservice;
    private String groupid;

    private List<GroupLevelBean> groupLevelBeanList = new ArrayList<>();
    private GroupLevelAdapter mAdapter ;

    private AlertDialog payDialog;
    PasswordEditText payPSD;

    private String level = "0";
    private String month= "0";
    private int type = 0;//0=升级；1=续费
    private Dialog dialog ;
    public static void start(Activity activity, String groupid){
        Intent intent = new Intent(activity, GroupLevelSelectActivity.class);
        intent.putExtra("groupid",groupid);
        activity.startActivity(intent);
    }
    public static void start(Activity activity, String groupid, int type){
        Intent intent = new Intent(activity, GroupLevelSelectActivity.class);
        intent.putExtra("groupid",groupid);
        intent.putExtra("type",type);
        activity.startActivity(intent);
    }

    @Override
    protected String getTitleText() {
        return "升级群";
    }
    String one_month;
    String three_months;
    String six_months;
    String a_year;
    @Override
    protected void initViews(Bundle savedInstanceState) {
        mPGservice = PGService.getInstance();
        groupid = getIntent().getStringExtra("groupid");
        type = getIntent().getIntExtra("type",0);

        mAdapter = new GroupLevelAdapter(GroupLevelSelectActivity.this, groupLevelBeanList);
        ImGroupEntivity mImGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, Long.parseLong(groupid));
        if (null!=mImGroupEntivity){
            mAdapter.setThisLevel(mImGroupEntivity.getLevel());
        }
        mAdapter.setType(type);
        //用户点击升级按钮的点击事件
        mAdapter.setOnclick(new GroupLevelAdapter.OnClickListener() {
            @Override
            public void OnClick(int type) {
                level = "" + type ;
                final UserEntivity user = ToolsUtils.getUser();
                /*if (user.getPayInfo() == null || user.getPayInfo().equals("")) {
                    //Toast.makeText(PayActivity.this, getString(R.string.please_set_pay_psd), Toast.LENGTH_SHORT).show();
                    showSetPSWdialog();
                    return;
                }
                showPayDialog();*/
                //dd();
                if(level.equals("1")){
                    one_month ="一个月(20元)";
                    three_months="三个月(60元)";
                    six_months="六个月(120元)";
                    a_year="一年(240元)";
                }else if(level.equals("2")){
                    one_month ="一个月(30元)";
                    three_months="三个月(90元)";
                    six_months="六个月(180元)";
                    a_year="一年(360元)";
                }else if (level.equals("3"))
                {
                    one_month ="一个月(50元)";
                    three_months="三个月(150元)";
                    six_months="六个月(300元)";
                    a_year="一年(600元)";
                }

                dialog = MyDialog.ShowDialog(GroupLevelSelectActivity.this, "",
                        new String[]{one_month,
                                three_months,
                                six_months,
                                a_year,
                        },
                        new MyDialog.DialogItemClickListener() {
                            @Override
                            public void confirm(String result) {
                                if (one_month.equals(result)){
                                    if (user.getPayInfo() == null || user.getPayInfo().equals("")) {
                                        //Toast.makeText(PayActivity.this, getString(R.string.please_set_pay_psd), Toast.LENGTH_SHORT).show();

                                        showSetPSWdialog();
                                        return;
                                    }
                                    month="1";
                                    showPayDialog();

                                }else if (three_months.equals(result)){
                                    //startActivity(new Intent(GroupLevelSelectActivity.this,SendCircleActivity.class));
                                    if (user.getPayInfo() == null || user.getPayInfo().equals("")) {
                                        //Toast.makeText(PayActivity.this, getString(R.string.please_set_pay_psd), Toast.LENGTH_SHORT).show();

                                        showSetPSWdialog();
                                        return;
                                    }
                                    month="3";
                                    showPayDialog();
                                }else if (six_months.equals(result)){
                                    //SendCircleActivity.start(GroupLevelSelectActivity.this, 2);
                                    if (user.getPayInfo() == null || user.getPayInfo().equals("")) {
                                        //Toast.makeText(PayActivity.this, getString(R.string.please_set_pay_psd), Toast.LENGTH_SHORT).show();

                                        showSetPSWdialog();
                                        return;
                                    }
                                    month="6";
                                    showPayDialog();
                                } else if (a_year.equals(result)){
                                    //SendCircleActivity.start(GroupLevelSelectActivity.this, 2);
                                    if (user.getPayInfo() == null || user.getPayInfo().equals("")) {
                                        //Toast.makeText(PayActivity.this, getString(R.string.please_set_pay_psd), Toast.LENGTH_SHORT).show();

                                        showSetPSWdialog();
                                        return;
                                    }
                                    month="12";
                                    showPayDialog();
                                }
                            }
                        });

                dialog.show();
            }
        });
        recycler_view.setLayoutManager(new LinearLayoutManager(this));
        recycler_view.setAdapter(mAdapter);
        queryGroupConfig();

    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_group_level_select;
    }

    /**
     * 查询群组等级
     */
    private void queryGroupConfig() {
        showProgress("");
        mPGservice.queryGroupConfig(ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<GroupLevelEntity>() {
            @Override
            public void onNext(final GroupLevelEntity friendEntivity) {
//                Log.i("info", "查询到的群成员==" + friendEntivity.getInfo().toString());
                groupLevelBeanList.addAll(friendEntivity.getInfo());
                mAdapter.notifyDataSetChanged();
                hideProgress();
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
                hideProgress();
            }
        });
    }


    /**
     * 升级群
     */
    private void payForGroupLevel( String pwd) {

       String userId=ToolsUtils.getMyUserId();
       //把需要传给后台的参数写成json然后加密传给后台，加密更安全
        com.alibaba.fastjson.JSONObject json = new JSONObject();
        json.put("groupId", groupid);
        json.put("level", level);
        json.put("pwd", pwd);
        json.put("userId", userId);
        json.put("month",month);//月份
        String content = RequestRSAUtils.setRsaContent(json);
        /*Map<String, Object> maps = new HashMap<>();
        maps.put("groupId", groupid);
        maps.put("level", level);
        maps.put("pwd", pwd);
        maps.put("userId", userId);
        String content = RequestRSAUtils.setRsaContent(maps);*/
        System.out.println("加密之后===========================："+content);
        showProgress("");
        mPGservice.payForGroupLevel(content).subscribe(new AbsAPICallback<ImGroupEntivity>() {
            @Override
            public void onNext(final ImGroupEntivity friendEntivity) {
                showToast("升级成功！");
                ImGroupEntivity mImGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, Long.parseLong(groupid));
                mImGroupEntivity.setLevel(level);
                mImGroupEntivity.setExpire(friendEntivity.getExpire());
                mImGroupEntivity.save();

                hideProgress();
                finish();
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
                switch (ex.getCode()){
                    case 2 :
                        showToast("支付密码不正确！");
                        break;
                    case 3 :
                        showToast("余额不足");
                        break;
                    case 4 :
                        showToast("只要群主可以升级");
                        break;
                }
                hideProgress();
            }
        });
    }


    private void showSetPSWdialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(GroupLevelSelectActivity.this);
        builder.setTitle(getResources().getString(R.string.tip_psw));
        builder.setMessage(getResources().getString(R.string.no_pay_psw));
        builder.setNegativeButton(getResources().getString(R.string.now_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setPositiveButton(getResources().getString(R.string.now_go), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(GroupLevelSelectActivity.this, NewPasswordActivity.class);
                intent.putExtra("type", getResources().getString(R.string.set_pay_psd));
                startActivity(intent);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    private void showPayDialog() {
        View dialog = LayoutInflater.from(this).inflate(R.layout.transfer_account_dialog, null);
        try {
            payDialog = new AlertDialog.Builder(this).setView(dialog).create();
            payDialog.show();
        }catch (Exception e){
            e.printStackTrace();
        }

        TextView payCancel = (TextView) dialog.findViewById(R.id.pay_cancel);
        TextView payCommit = (TextView) dialog.findViewById(R.id.pay_commit);
//        payPSD = ((EditText) dialog.findViewById(R.id.pay_psd));
        payPSD = ((PasswordEditText) dialog.findViewById(R.id.passwordInputView));
        payPSD.setSpacingWidth(0);
        popupKeyboard(payPSD);
        payCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                payDialog.dismiss();
            }
        });
        payCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String pwd = payPSD.getText().toString().trim();
                if ("".equals(pwd)) {
                    new ToastUtils().showLongToast(getResources().getString(R.string.please_import_pay_psd));
                } else {
//                    dopaymoney(pwd,imMessage.getDestid());
//                    payForGroupJoin(pwd, "" + mImGroupEntivity.getId());
//                    payForGroupJoin
                    //  validatePayPwd(pwd);
                    payForGroupLevel(MD5.MD532(pwd));
                    payDialog.dismiss();
                }
            }
        });
    }

    private void popupKeyboard(final PasswordEditText editText) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(editText, 0);
                           }

                       },
                200);
    }


}
